
const MomoXafPageTag = require("./momoXafPageTag.js");
const Constant = require("./constant.js");
const ApiUrl = require("./baseApiUrl.js");



// 操作 登录
const doLogin = () => {
    let editList = className("EditText").find();
    // console.log("doLogin-判断是否为登录页-editList ", editList.length)
    console.log(Constant.UI_SDK_VERSION + "doLogin-开始操作登录");
    for (let index = 0; index < editList.length; index++) {
        let tv = editList[index];
        let curText = tv.text() || ""
        // console.log(Constant.UI_SDK_VERSION + "doLogin-当前: "+ index+ ", 内容: ", curText)

        if (curText.indexOf(MomoXafPageTag.loginPageTag1) !== -1) {
            console.log(Constant.UI_SDK_VERSION + "doLogin-设置登录手机号: ", Constant.getMtn());
            tv.setText(Constant.getMtn());

            sleep(1000);
            console.log(Constant.UI_SDK_VERSION + "doLogin-点击登录");
            click(MomoXafPageTag.loginPageTag3);
            sleep(500)
            click(MomoXafPageTag.loginPageTag3);
            sleep(500)
            click(MomoXafPageTag.loginPageTag3);

            editList.length = 0;
            editList = null;
            return true;
        }
    }

    editList.length = 0;
    editList = null;
    console.log(Constant.UI_SDK_VERSION + "doLogin-操作登录结束: 当前不是登录页")
    return false;
}

// 操作 登录-pin
const doPin = () => {
    let editList = className("EditText").find();
    // console.log(Constant.UI_SDK_VERSION + "doLogin-判断是否为登录页-editList ", editList.length)
    console.log(Constant.UI_SDK_VERSION + "doPin-开始操作登录-pin");
    if (editList.length > 0) {
        let tv = editList[0];
        console.log(Constant.UI_SDK_VERSION + "doPin-设置登录PIN: ", Constant.getPin());
        tv.setText(Constant.getPin());
        sleep(1000);
        click(MomoXafPageTag.pinPageTag2);
        sleep(500)
        click(MomoXafPageTag.pinPageTag2);

        editList.length = 0;
        editList = null;
        return true;
    }

    editList.length = 0;
    editList = null;
    console.log(Constant.UI_SDK_VERSION + "doPin-操作登录结束: 当前不是登录-pin页")
    return false;
}

// 操作 打开 send money 页
const doOpenSendMoneyPage = () => {
    // 点击 Send money
    console.log(Constant.UI_SDK_VERSION + "doOpenSendMoneyPage-开始操作打开 Send money 页");
    sleep(500);
    click(MomoXafPageTag.homePageTag3);
    sleep(500);
    click(MomoXafPageTag.homePageTag3);
    return true;
}

// 操作 打开 send money 页
const doOpenMtnMoMoPage = () => {
    // 点击 Send money
    console.log(Constant.UI_SDK_VERSION + "doOpenSendMoneyPage-开始操作打开 To MTN MoMo 页");
    sleep(500);
    click(MomoXafPageTag.sendMoneyMtnPageTag4)
    // sleep(500);
    // click("To MTN MoMo")
    return true;
}

// 操作 mtn account input
const doMtnMoMoAccountInput = (targetMtn, targetAmount, targetReference) => {
    let editList = className("EditText").find();
    let textList = className("TextView").find();

    console.log(Constant.UI_SDK_VERSION + "doMtnMoMoAccountInput-开始操作 mtn momo account input");
    console.log(Constant.UI_SDK_VERSION + "doMtnMoMoAccountInput-targetMtn", targetMtn);
    console.log(Constant.UI_SDK_VERSION + "doMtnMoMoAccountInput-targetAmount", targetAmount);
    console.log(Constant.UI_SDK_VERSION + "doMtnMoMoAccountInput-targetReference", targetReference);

    if (targetMtn.length > 0 && targetAmount.length > 0) {

        let findTag1 = false;
        let findTag2 = false;
        let findTag3 = false;

        let findTagSend = false;

        for (let index = 0; index < editList.length; index++) {
            let tv = editList[index];
            let curText = tv.text() || ""
            // console.log(Constant.UI_SDK_VERSION + "doLogin-当前: " + index + ", 内容: ", curText)

            if (curText.indexOf(MomoXafPageTag.sendMoneyMtnAccountInputPageHintTag1) !== -1) {
                console.log(Constant.UI_SDK_VERSION + "doMtnMoMoAccountInput-设置 mtn account input number: ", targetMtn);
                tv.setText(targetMtn);
                findTag1 = true;
            }
            if (curText.indexOf(MomoXafPageTag.sendMoneyMtnAccountInputPageHintTag2) !== -1) {
                console.log(Constant.UI_SDK_VERSION + "doMtnMoMoAccountInput-设置 mtn account input amount: ", targetAmount);
                tv.setText(targetAmount);
                findTag2 = true;
            }
            if (curText.indexOf(MomoXafPageTag.sendMoneyMtnAccountInputPageHintTag3) !== -1) {
                console.log(Constant.UI_SDK_VERSION + "doMtnMoMoAccountInput-设置 mtn account input amount: ", targetReference);
                tv.setText(targetReference);
                findTag3 = true;
            }
        }

        // 查找 continuer
        for (let index = 0; index < textList.length; index++) {
            let tv = textList[index];
            let curText = tv.text() || ""
            // console.log(Constant.UI_SDK_VERSION + "doLogin-当前: " + index + ", 内容: ", curText)

            if (curText.indexOf(MomoXafPageTag.sendMoneyMtnAccountInputPageSendTag1) !== -1) {
                console.log(Constant.UI_SDK_VERSION + "doMtnMoMoAccountInput-找到 send 按键");
                findTagSend = true;
                break;
            }
        }

        sleep(2 * 1000)

        // 注意，找不到 send ，只能通过 bounds 来触发

        if (findTag1 && findTag2 && findTag3) {
            console.log(Constant.UI_SDK_VERSION + "doMtnMoMoAccountInput-点击 关闭键盘");
            // back();
            // bounds(0, 1590, 10, 1613).clickable().click()
            // click(10, 1600);

            sleep(1 * 1000)

            console.log(Constant.UI_SDK_VERSION + "doMtnMoMoAccountInput-点击 确认");
            // click("Send");
            //bounds(36, 1518, 684, 1613).clickable().click()

            if (findTagSend) {
                console.log(Constant.UI_SDK_VERSION + "doMtnMoMoAccountInput-找到 send 按键");

                click(MomoXafPageTag.sendMoneyMtnAccountInputPageSendTag1);
                sleep(500)
                click(MomoXafPageTag.sendMoneyMtnAccountInputPageSendTag1);
                sleep(500)
                click(MomoXafPageTag.sendMoneyMtnAccountInputPageSendTag1);
                sleep(500)
            } else {
                console.log(Constant.UI_SDK_VERSION + "doMtnMoMoAccountInput-找不到 send 按键");

                let gx = device.width / 2;
                let gy = device.height - 60;
                console.log(gx + ", " + gy);
                click(gx, gy);
                sleep(500);
            }

            editList.length = 0;
            editList = null;

            textList.length = 0;
            textList = null;
            return true;
        }
    }

    editList.length = 0;
    editList = null;

    textList.length = 0;
    textList = null;
    console.log(Constant.UI_SDK_VERSION + "doMtnMoMoAccountInput-操作登录结束: 当前不是 mtn momo account input 页")
    return false;
}

// 操作 点击 Complete 转账
const doClickTransferComleted = () => {
    // 点击 Send money
    console.log(Constant.UI_SDK_VERSION + "doClickTransferComleted-开始操作点击 Complete");
    sleep(500);
    click(MomoXafPageTag.sendMoneyMtnAccountConfirmPageTag2);
    sleep(500);
    click(MomoXafPageTag.sendMoneyMtnAccountConfirmPageTag2);
    sleep(2000);
    return true;
}

// 操作 点击 Done 结束返回
const doClickTransferDoneAndGoBack = () => {
    // 点击 back
    console.log(Constant.UI_SDK_VERSION + "doClickTransferDoneAndGoBack-开始操作点击 Done");
    click(MomoXafPageTag.sendMoneyMtnSuccessPageDoneTag1);
    sleep(500);
    click(MomoXafPageTag.sendMoneyMtnSuccessPageDoneTag1);
    return true;
}

// 操作 点击 Done 结束返回
const doClickTransferPreFailAndGoBack = () => {
    // 点击 back
    console.log(Constant.UI_SDK_VERSION + "doClickTransferPreFailAndGoBack-开始操作点击 Done");
    click(MomoXafPageTag.sendMoneyMtnSuccessPageFailTag1);
    sleep(500);
    click(MomoXafPageTag.sendMoneyMtnSuccessPageFailTag1);
    sleep(1000);
    back();
    return true;
}

// 操作 点击 Done 结束返回
const doClickTransferFailAndGoBack = () => {
    // 点击 back
    console.log(Constant.UI_SDK_VERSION + "doClickTransferFailAndGoBack-开始操作点击 Done");
    click(MomoXafPageTag.sendMoneyMtnSuccessPageFailTag1);
    sleep(500);
    click(MomoXafPageTag.sendMoneyMtnSuccessPageFailTag1);
    return true;
}

// 操作 点击 Transactions
const doClickTransacitons = () => {
    // 点击 Transactions
    console.log(Constant.UI_SDK_VERSION + "doClickTransacitons-开始操作点击 Transactions");
    click(MomoXafPageTag.homePageTag4)
    return true;
}

// 操作 点击 SEE ALL
const doClickSeeAll = () => {
    // 点击 SEE ALL
    console.log(Constant.UI_SDK_VERSION + "doClickSeeAll-开始操作点击 SEE ALL");
    // click("SEE ALL")
    return true;
}

// 操作 开始查询数据
const doGetBillDetails = () => {
    // 判断是否为流水列表页
    // if (!PageUtil.isTransactionListPage()) {
    //     events.emitter().emit(PageTag.SESSION_TIME_OUT);
    //     return;
    // }

    let detailInfo = {
        currentBalance: "",
        phone: Constant.getMtn(),
        bills: []
    }

    let textList = className("TextView").find();
    console.log(Constant.UI_SDK_VERSION + "doGetBillDetails-找到了内容数 ", textList.length)

    for (let index = 0; index < textList.length; index++) {
        console.log(Constant.UI_SDK_VERSION + "doGetBillDetails-当前 ", index)
        let tv = textList[index];
        let curText = tv.text()
        console.log(Constant.UI_SDK_VERSION + "doGetBillDetails-内容 ", curText)

        if (curText !== "") {
            // 1、找到 Current balance
            if (curText.indexOf(MomoXafPageTag.transactionListPageTag3) !== -1) {
                const currentBalanceValueTv = textList[(index + 1)];
                detailInfo.currentBalance = currentBalanceValueTv.text() || "";

                console.log(Constant.UI_SDK_VERSION + "doGetBillDetails-找到了 ", MomoXafPageTag.transactionListPageTag3)
                console.log(Constant.UI_SDK_VERSION + "============")
            }

            // 2、找到 YOUR LAST 10 TRANSACTIONS
            if (curText.indexOf(MomoXafPageTag.transactionListPageTag2) !== -1) {
                console.log(Constant.UI_SDK_VERSION + "doGetBillDetails-找到了 ", MomoXafPageTag.transactionListPageTag2)
                console.log(Constant.UI_SDK_VERSION + "============")

                // 0 dateTime
                const dateTimeIndex = (index + 1);
                if (textList.length > dateTimeIndex) {
                    // 递归查询下一个菜单
                    const nextBillItemNext = dateTimeIndex;
                    getNextBillItemV2(textList, nextBillItemNext, detailInfo);
                }

                // 输出所有内容
                console.log(Constant.UI_SDK_VERSION + "doGetBillDetails-输出所有内容: ")
                console.log(detailInfo)
                // 跳出循环，结束
                break;
            }
        }
    }

    console.log(Constant.UI_SDK_VERSION + "doGetBillDetails-等待2秒")
    sleep(2000)
    // 保存数据
    console.log(Constant.UI_SDK_VERSION + "doGetBillDetails-开始保存流程信息")
    // --- temp close
    if (false) {
        let url = ApiUrl.saveBills();
        HttpUtil.sendPostSync(url, detailInfo);
    }

    detailInfo.bills.length = 0;
    detailInfo.bills = [];

    textList.length = 0;
    textList = null;
    console.log(Constant.UI_SDK_VERSION + "doGetBillDetails-上传数据中, 等待5秒")
    sleep(5 * 1000);
}

// 递归查询下一个菜单
const getNextBillItemV2 = (textList, dateTimeIndex, resultDetailInfo) => {
    console.log(Constant.UI_SDK_VERSION + "getNextBillItemV2-递归查询下一个菜单V2")
    if (textList && textList.length > dateTimeIndex) {
        // 0 dateTime
        let dateTimeTv = textList[dateTimeIndex];

        // 账单信息
        let billItem = {
            dateTime: "",
            amount: "",
            name: "",
            txnId: "",
            type: "",
            txnFee: "",
            toAddr: Constant.getMtn(),
            fromAddr: "",
            phone: Constant.getMtn()
        };
        billItem.dateTime = (dateTimeTv.text() || "").trim();

        // 是否为支出
        let isPayOut = true;

        // 1 amount
        let amountIndex = (dateTimeIndex + 1);
        if (textList.length > amountIndex) {
            let amountTv = textList[amountIndex];
            billItem.amount = amountTv.text() || "";

            // 收入
            if (billItem.amount.startsWith("+")) {
                isPayOut = false;
            }
        }

        if (isPayOut) {
            billItem.fromAddr = Constant.getMtn();
        }

        // 2 name
        let nameIndex = (dateTimeIndex + 2);
        if (textList.length > nameIndex) {
            let nameTv = textList[nameIndex];
            billItem.name = nameTv.text() || "";
        }

        // name 下一个标记
        let nameIndexNext = (nameIndex + 1);

        // 一直找 txnid
        let txnIdIndex = -1;
        for (let i = nameIndexNext; i < textList.length; i++) {
            let findTv = textList[i];
            let findTvText = findTv.text() || "";

            // 如果碰到 -xxx/+xxx 就退出循环
            if (findTvText.startsWith("-")) {
                break;
            }
            if (findTvText.startsWith("+")) {
                break;
            }

            if (findTvText.indexOf(MomoXafPageTag.transactionListItemTagTxnId) !== -1) {
                txnIdIndex = (i + 1);
                if (textList.length > txnIdIndex) {
                    let txnIdTv = textList[txnIdIndex];
                    billItem.txnId = txnIdTv.text() || "";
                }
            }
        }

        // 一直找 type
        let typeIndex = -1;
        for (let i = nameIndexNext; i < textList.length; i++) {
            let findTv = textList[i];
            let findTvText = findTv.text() || "";

            // 如果碰到 -xxx/+xxx 就退出循环
            if (findTvText.startsWith("-")) {
                break;
            }
            if (findTvText.startsWith("+")) {
                break;
            }

            if (findTvText.indexOf(MomoXafPageTag.transactionListItemTagTxnType) !== -1) {
                typeIndex = (i + 1);
                if (textList.length > typeIndex) {
                    let txnIdTv = textList[typeIndex];
                    billItem.type = txnIdTv.text() || "";
                }
            }
        }

        // 一直找 txn fee
        let txnFeeIndex = -1;
        for (let i = nameIndexNext; i < textList.length; i++) {
            let findTv = textList[i];
            let findTvText = findTv.text() || "";

            // 如果碰到 -xxx/+xxx 就退出循环
            if (findTvText.startsWith("-")) {
                break;
            }
            if (findTvText.startsWith("+")) {
                break;
            }

            if (findTvText.indexOf(MomoXafPageTag.transactionListItemTagTxnFee) !== -1) {
                txnFeeIndex = (i + 1);
                if (textList.length > txnFeeIndex) {
                    let txnIdTv = textList[txnFeeIndex];
                    billItem.txnFee = txnIdTv.text() || "";
                }
            }
        }

        // 一直找 to
        let toIndex = -1;
        for (let i = nameIndexNext; i < textList.length; i++) {
            let findTv = textList[i];
            let findTvText = findTv.text() || "";

            // 如果碰到 -xxx/+xxx 就退出循环
            if (findTvText.startsWith("-")) {
                break;
            }
            if (findTvText.startsWith("+")) {
                break;
            }

            if (findTvText.indexOf(MomoXafPageTag.transactionListItemTagTo) !== -1) {
                toIndex = (i + 1);
                if (textList.length > toIndex) {
                    let txnIdTv = textList[toIndex];
                    billItem.toAddr = txnIdTv.text() || "";
                }
            }
        }

        // 一直找 from
        let fromIndex = -1;
        for (let i = nameIndexNext; i < textList.length; i++) {
            let findTv = textList[i];
            let findTvText = findTv.text() || "";

            // 如果碰到 -xxx/+xxx 就退出循环
            if (findTvText.startsWith("-")) {
                break;
            }
            if (findTvText.startsWith("+")) {
                break;
            }

            if (findTvText.indexOf(MomoXafPageTag.transactionListItemTagFrom) !== -1) {
                fromIndex = (i + 1);
                if (textList.length > fromIndex) {
                    let txnIdTv = textList[fromIndex];
                    billItem.fromAddr = txnIdTv.text() || "";
                }
            }
        }

        // 添加账单
        if (resultDetailInfo.bills === null) {
            resultDetailInfo.bills = []
        }
        resultDetailInfo.bills.push(billItem)


        // 最后查找 date 
        let nextBillItemNext = textList.length;
        for (let i = nameIndexNext; i < textList.length; i++) {
            let findTv = textList[i];
            let findTvText = findTv.text() || "";

            // 如果碰到 -xxx/+xxx 就退出循环
            if (findTvText.startsWith("-")) {
                nextBillItemNext = (i - 1);
                break;
            }
            if (findTvText.startsWith("+")) {
                nextBillItemNext = (i - 1);
                break;
            }
        }

        // 递归查询下一个菜单
        getNextBillItemV2(textList, nextBillItemNext, resultDetailInfo);

    } else {
        console.log(Constant.UI_SDK_VERSION + "getNextBillItemV2-递归结束, 没有更多")
    }
};

module.exports = {
    doLogin: doLogin,
    doPin: doPin,
    doOpenSendMoneyPage: doOpenSendMoneyPage,
    doOpenMtnMoMoPage: doOpenMtnMoMoPage,
    doMtnMoMoAccountInput: doMtnMoMoAccountInput,
    doClickTransferComleted: doClickTransferComleted,
    doClickTransferPreFailAndGoBack: doClickTransferPreFailAndGoBack,
    doClickTransferFailAndGoBack: doClickTransferFailAndGoBack,
    doClickTransferDoneAndGoBack: doClickTransferDoneAndGoBack,
    doClickTransacitons: doClickTransacitons,
    doClickSeeAll: doClickSeeAll,
    doGetBillDetails: doGetBillDetails
};